/* global process */
import fs from 'fs';
import https from 'https';
import http from 'http';

// 配置后端 URL
const backendUrl = 'http://localhost:8080/api/v3/api-docs';

console.log('📥 正在获取最新的API文档...');

function fetchApiDocs() {
    return new Promise((resolve, reject) => {
        const client = backendUrl.startsWith('https') ? https : http;

        const url = new URL(backendUrl);
        const options = {
            hostname: url.hostname,
            port: url.port,
            path: url.pathname + url.search,
            method: 'GET',
            headers: {
                'Accept': 'application/json;charset=UTF-8'
            }
        };

        const req = client.request(options, (res) => {
            let data = '';

            res.on('data', (chunk) => {
                data += chunk;
            });

            res.on('end', () => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    // 验证是否为有效的 JSON
                    JSON.parse(data);
                    resolve(data);
                } else {
                    reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
                }
            });
        });

        req.on('error', (error) => {
            reject(error);
        });

        req.end();
    });
}

fetchApiDocs()
    .then((data) => {
        fs.writeFileSync('api-docs.json', data, 'utf8');
        console.log('✅ API文档已更新');
    })
    .catch((error) => {
        console.error('❌ 获取API文档失败:', error.message);
        process.exit(1);
    });
